from screeninfo import get_monitors, Monitor
from pygetwindow import getAllWindows, Win32Window
import win32api
import win32gui
import win32con
import time


def restore_window(w: Win32Window):
    # 获取窗口的状态
    hwnd = w._hWnd
    placement = win32gui.GetWindowPlacement(hwnd)
    if placement[1] == win32con.SW_SHOWMAXIMIZED:
        # 如果窗口是最大化的，恢复到正常状态
        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
    elif placement[1] == win32con.SW_SHOWMINIMIZED:
        # 如果窗口是最小化的，恢复到正常状态
        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
        win32gui.SetForegroundWindow(hwnd)  # 将窗口带到前台
    # else:
    #     print("Window is already in a normal state.")


def get_visible_windows():
    monitors = get_monitors()
    mx_width = max(m.width for m in monitors)
    mx_height = max(m.height for m in monitors)
    windows: list[Win32Window] = []
    for w in getAllWindows():
        title = w.title.strip()
        if not title:
            continue
        if (w.isMaximized or w.isMinimized) or (
            w.height <= mx_height and w.width <= mx_width
        ):
            windows.append(w)
    return windows


# print([w.title for w in get_visible_windows()])


# 获取当前鼠标位置
def get_mouse_pos():
    return win32api.GetCursorPos()


def get_current_monitor():
    x, y = get_mouse_pos()
    for monitor in sorted(get_monitors(), key=lambda m: m.x, reverse=True):
        if x >= monitor.x:
            return monitor


def has_monitor_contains_window(monitor: Monitor, window: Win32Window):
    if window.isMaximized or window.isMinimized:
        return False
    left = monitor.x
    top = monitor.y
    width = monitor.width
    height = monitor.height
    return window.left >= left and window.right <= left + width


def move_window(w: Win32Window, monitor: Monitor):
    is_maximized = w.isMaximized
    if has_monitor_contains_window(monitor, w):
        return
    try:
        restore_window(w)
        w.moveTo(monitor.x, monitor.y)
        if is_maximized:
            w.maximize()
        time.sleep(0.1)
        print("Move", w.title, (monitor.x, monitor.y))
    except:
        print("Move Failed:", w.title)


def move_all_windows(monitor: Monitor):
    active_window = None
    for w in get_visible_windows():
        if w.isActive:
            active_window = w
        move_window(w, monitor)
    active_window.activate()
    print("All windows are moved!")


if __name__ == "__main__":
    move_all_windows(get_current_monitor())
